/**
 * Name: Avinash Sridhar	G Number: G00861300
 */

package tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;

import tcp.Server.PhonebookEntry;

public class ChildRequestHandler extends Thread {

	ArrayList<PhonebookEntry> mPhonebook;
	ServerSocket mClientSocketPort;
	ServerSocket mChildrenSocketPort;
	int mParentSocketPort;

	/**
	 * @throws IOException 
	 * 
	 */
	public ChildRequestHandler(ArrayList<PhonebookEntry> phonebook, ServerSocket clientSocketPort, ServerSocket childrenSocketPort, int parentSocketPort) throws IOException {

		mPhonebook = phonebook;
		mClientSocketPort = clientSocketPort;
		mChildrenSocketPort = childrenSocketPort;
		mParentSocketPort = parentSocketPort;

	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		try{ 
			System.out.println("TCP Server Initialized and Listening for TCP Child Nodes at children port <" + mChildrenSocketPort.getLocalPort() + ">...");
			while (true) {
				/* Params:
				 * clientSocket - contains Client's current request to the Server
				 * phonebook - contains phonebook of current Server
				 * clientSocketPort - contains the clientSocketPort for this Server
				 * childrenSocketPort - contains the childrenSocketPort for this Server
				 * parentSocketPort - contains the parentSocketPort number for this Server
				 */
				new LookupService(mChildrenSocketPort.accept(), mPhonebook, mClientSocketPort.getLocalPort(), mChildrenSocketPort.getLocalPort(), mParentSocketPort).start();
			}
		} catch (IOException e) {
			System.out.println("Could not listen on port " + mChildrenSocketPort.getLocalPort());
			System.exit(0);
		}
	}

}
